package com.fy.springmvc2.controller;

import com.fy.springmvc2.entity.User;
import com.fy.springmvc2.service.intf.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@Transactional(rollbackFor = Exception.class)  // 遇到异常的情况下回滚事务
public class UserController {
    @Resource
    UserService service;

    @RequestMapping("/save")
    public int save(User user){
        return service.save(user);
    }

    @RequestMapping("/queryAll")
    public List<User> selectAll(){
        return service.selectAll();
    }

    @GetMapping("/page/{num}")
    public String getUserByPage(@PathVariable("num") Integer pageIndex, Model model) {
        if (pageIndex <= 1) {
            pageIndex = 1;
        }
        PageInfo<User> pageInfo = service.selectPage(pageIndex, 2);
        model.addAttribute("pageInfo", pageInfo);
        return "welcome";
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        // 直接跳转到添加页面
        return "add";
    }


    @RequestMapping("/add")
    public String addUser(User user){
        // 补全注册时间
        user.setCtime(new Date());
        service.save(user);
        // 添加完成后重定向到用户列表页
        return "redirect:/page/1";
    }
}
